namespace sort
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            button1.Click += button1_Click;
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            // 从dataGridView1读取数据
            int rowCount = dataGridView1.Rows.Count;
            int colCount = dataGridView1.Columns.Count;
            int[,] originalArray = new int[rowCount, colCount];
            int validRowCount = 0;
            int validColCount = 0;

            // 读取有效数据（跳过空行）
            for (int i = 0; i < rowCount; i++)
            {
                if (dataGridView1.Rows[i].IsNewRow) break;
                validRowCount++;
                validColCount = Math.Max(validColCount, colCount);
                for (int j = 0; j < colCount; j++)
                {
                    if (int.TryParse(dataGridView1.Rows[i].Cells[j].Value?.ToString(), out int value))
                    {
                        originalArray[i, j] = value;
                    }
                    else
                    {
                        originalArray[i, j] = 0; // 默认值
                    }
                }
            }

            if (validRowCount == 0) return;

            // 将二维数组转换为一维数组进行排序
            int[] newArray = new int[validRowCount * validColCount];
            int index = 0;
            for (int i = 0; i < validRowCount; i++)
            {
                for (int j = 0; j < validColCount; j++)
                {
                    newArray[index++] = originalArray[i, j];
                }
            }

            // 对一维数组进行排序
            Array.Sort(newArray);

            // 将排序后的一维数组转换回二维数组
            int[,] sortedArray = new int[validRowCount, validColCount];
            index = 0;
            for (int i = 0; i < validRowCount; i++)
            {
                for (int j = 0; j < validColCount; j++)
                {
                    sortedArray[i, j] = newArray[index++];
                }
            }

            // 清空dataGridView2
            dataGridView2.Rows.Clear();

            // 在dataGridView2中显示排序后的数组
            for (int i = 0; i < validRowCount; i++)
            {
                int rowIndex = dataGridView2.Rows.Add();
                for (int j = 0; j < validColCount; j++)
                {
                    dataGridView2.Rows[rowIndex].Cells[j].Value = sortedArray[i, j];
                }
            }
        }
    }
}
